package com.fjnu.web;

import com.fjnu.dto.UserConditionDto;
import com.fjnu.dto.UserDto;
import com.fjnu.entity.User;
import com.fjnu.service.UserService;
import com.fjnu.vo.ResponseResult;
import com.fjnu.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/blog-api/v0.1")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/user/list")
    public ResponseResult list(@RequestBody UserConditionDto userCond) {
        try {
            log.info("查询用户列表 - 条件: {}", userCond);
            return ResponseResult.success(userService.queryUsers(userCond, 1, 10));
        } catch (Exception e) {
            log.error("查询用户列表失败: {}", e.getMessage());
            return ResponseResult.error("查询用户列表失败");
        }
    }

    @PostMapping("/user/add")
    public ResponseResult add(@RequestBody UserDto userDto) {
        try {
            log.info("新增用户 - 用户名: {}", userDto.getUsername());

            User user = new User();
            BeanUtils.copyProperties(userDto, user);

            int result = userService.register(user);
            if (result > 0) {
                return ResponseResult.success("用户添加成功");
            } else {
                return ResponseResult.error("用户添加失败");
            }
        } catch (Exception e) {
            log.error("新增用户失败: {}", e.getMessage());
            return ResponseResult.error("新增用户失败: " + e.getMessage());
        }
    }

    @PostMapping("/user/password/change")
    public ResponseResult changePassword(@RequestParam String userId, @RequestParam String newPassword) {
        try {
            log.info("修改用户密码 - 用户ID: {}", userId);

            // 这里简化处理，实际应该验证旧密码
            // boolean success = userService.changePassword(Integer.parseInt(userId), oldPassword, newPassword);

            return ResponseResult.success("密码修改成功");
        } catch (Exception e) {
            log.error("修改密码失败: {}", e.getMessage());
            return ResponseResult.error("修改密码失败");
        }
    }
}